<template>
  <div>
    <el-card style="width: 50%">
      <el-form :rules="rules" ref="ruleForm" :model="user" label-width="80px">
        <el-form-item label="原始密码" prop="password">
          <el-input show-password v-model="user.password" placeholder="原始密码" disabled></el-input>
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input show-password v-model="user.newPassword" placeholder="新密码"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input show-password v-model="user.confirmPassword" placeholder="确认密码"></el-input>
        </el-form-item>
        <div style="text-align: center; margin-bottom: 20px">
          <el-button type="primary" @click="update">确 认 修 改</el-button>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<script>
export default {
  name: "Password",
  data() {
    // 密码校验
    const validatePassword = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入确认密码'))
      } else if (value !== this.user.newPassword) {
        callback(new Error('两次密码不一致'))
      } else {
        callback();
      }
    }
    return {
      user: JSON.parse(localStorage.getItem('power-user' || '{}')),
      rules: {
        password: [{required: true, message: '请输入原始密码', trigger: 'blur'},],
        newPassword: [{required: true, message: '请输入新密码', trigger: 'blur'},],
        confirmPassword: [{validator: validatePassword, required: true, trigger: 'blur'},],
      }
    }
  },
  created() {
    // console.log(this.user)
  },
  methods: {
    update() {
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          // 更新一下密码然后再存储到数据库
          this.user.password = this.user.newPassword
          // 保存当前的用户信息到数据库
          this.$request.post('/user/update', this.user).then(res => {
            if (res.code === '200') {
              // 成功修改
              this.$message.success("修改成功")
              // 清除当前用户存储的数据
              localStorage.removeItem("power-user")
              // 跳转登录页面重新登录
              this.$router.push('/login')
            } else {
              this.$message.error(res.msg)
            }
          })
        }
      })
    },
  }
}
</script>

<style scoped>
/*deep 样式穿透*/
/deep/ .el-form-item__label {
  font-weight: bold;
}
</style>